#!/usr/bin/python
# -*- coding: utf-8 -*-

import Image
import sys

def roberts_cross(im) :
	pix = im.load()
	for x in range(im.size[0]-1):
                for y in range(im.size[1]-1):
                     pix[x,y] = pix[x,y] - pix[x+1, y+1]   
	return im


#Main処理
if __name__ == '__main__':
	argvs = sys.argv
	argc  = len(argvs)
	if ( argc != 2 ):
		print "Usage: img-tool <FileName>"
		sys.exit(1)  
	im = Image.open(argvs[1])
	nim = im.copy()
	(width, height) = im.size	

#1. 2値化
	nim = nim.convert("1")
	nim.save("/tmp/result.1.pgm")

#2. 行SCAN＆統計
	line_sum = []
	pix = nim.load()
	for x in range(height):
		cnt = 0
                for y in range(width):
                       if pix[y, x] == 0:
				cnt = cnt + 1 
		line_sum.append(cnt)

#3. 騒音対策
	min_pix = 1	#決め方要検討
	for x in range(height):
		if ( line_sum[x] <= min_pix ):
			line_sum[x] = 0
		else:
			line_sum[x] = line_sum[x] - min_pix 


#4. DOCの正当性チェック(SKIP)

#5. 行分け (zero_counter > 1)
	blocks = []
	tStart = 0
	tEnd   = 0
	bFirst = True
	zero_counter = 0 
	for x in range(height):
		if ( line_sum[x] != 0 ):
			if ( bFirst ) :
				bFirst = False
				tStart = x
			zero_counter = 0
		else:
			if ( not bFirst and zero_counter > 1 ) :
				tEnd = x			
				bFirst = True
				blocks.append((tStart, tEnd))
			zero_counter = zero_counter + 1

#6.行ブロック有効性判断

#7.行ブロックごとの文字分け
	blocks_detail = []
	for idx in range(len(blocks)):
		list   = []
		s, e = blocks[idx]
		for x in range(width):
			t = 0
			for y in range(s, e+1):
				t = t + (1 if pix[x,y] == 0 else 0 )					
			list.append(t)
		zero_cnt = 0
		char_cnt = 0
		base_idx = 0
		detail = []
		for v in list:
			if ( v != 0 ):
				if ( zero_cnt == 1):
					char_cnt = char_cnt + 1	
				if ( zero_cnt > 1 and char_cnt >=1 ):
					detail.append((base_idx - char_cnt - zero_cnt, base_idx - zero_cnt))
					char_cnt = 0
				char_cnt = char_cnt + 1
				zero_cnt = 0	
			else:
				zero_cnt = zero_cnt + 1
			base_idx = base_idx + 1
		blocks_detail.append(detail)	

#5.5 画像表示
	nim = im.copy()
	pix = nim.load()
	idx = 0
	for s,e in blocks:
		for p in range(width):
			pix[p, s] = 0 
			pix[p, e] = 0
		for f, l in blocks_detail[idx]:
			for z in range(s, e):	
				pix[f, z ] = 0
				#pix[l, z ] = 0
			
		idx = idx + 1		
	nim.save('/tmp/result.pgm')
